const urlUtil = require('url');
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');

const adapter = new FileSync('db/tfcaijing.json');
const db = low(adapter);

db.defaults({ 'columns': {}, 'column_reqs': {}, 'updated': 0 }).write();

const columns = {};

const column_list_req_url = 'https://crab.tfcaijing.com/app/news/newsflashcolumn/list';
const column_detail_req_url = 'https://crab.tfcaijing.com/app/news/newsflash/listByColumnId';

//anyproxy refer: https://github.com/alibaba/anyproxy/tree/master/rule_sample

module.exports = {
    summary: 'a rule to hack response',
    * beforeSendRequest(requestDetail) {
        if (requestDetail.url.startsWith(column_detail_req_url)) {
        	let urlobj = new URL(requestDetail.url);
        	let columnId = urlobj.searchParams.get('columnId');
        	if(columnId && columns[columnId]){
        		let columnName = columns[columnId];
        		let pageNum = urlobj.searchParams.get('pageNum');
	        	let pageSize = urlobj.searchParams.get('pageSize');
	            let newRequestOptions = requestDetail.requestOptions;
	            let headers = newRequestOptions.headers;
	            let systemVersion = headers['systemVersion'];
	            let systemId = headers['systemId'];
	            let sign = headers['sign'];
	            db.set('column_reqs.'+columnName, {
	            	'headers':{
	            		systemVersion,
	            		systemId,
	            		sign
	            	},
	            	'query':{
	            		columnId,
	            		pageNum,
	            		pageSize
	            	},
	            	'curl':`curl --request GET --url 'https://crab.tfcaijing.com/app/news/newsflash/listByColumnId?columnId=${columnId}&pageNum=1&pageSize=10' --header 'sign: ${sign}' --header 'systemid: ${systemId}' --header 'systemversion: ${systemVersion}'`,
	            	'updated':new Date()
	            }).write();
        	}
            /*
            return {
      		    requestOptions: newRequestOptions
            };
            */
        }
    },
    * beforeSendResponse(requestDetail, responseDetail) {
        if (requestDetail.url.startsWith(column_list_req_url)) {
            let newResponse = responseDetail.response;
            let body = newResponse.body.toString();
            try {
                let json_data = JSON.parse(body);
                if (json_data['data'] && json_data['data'].length > 0) {
                    for (let c of json_data['data']) {
                        columns[c['columnUid']] = c['columnTitle'];
                    }
                    db.set('columns', columns).write();
                    db.set('updated', new Date()).write();
                }
            } catch (e) {

            }
            /*
            return new Promise((resolve, reject) => {
	            // setTimeout(() => { // delay
	            resolve({ response: newResponse });
	            // }, 1000);
	        });
	        */

        }
    },
};